import {
	RouterMount,
	createRouter
} from 'uni-simple-router';
import NProgress from 'nprogress';
const router = createRouter({
	platform: process.env.VUE_APP_PLATFORM,
	routes: [...ROUTES]
});

import Cookies from 'js-cookie';
import axios from 'axios';
//全局路由前置守卫
router.beforeEach(async (to, from, next) => {
	if (to.path != from.path) {
		NProgress.start();

		let [page, controller, action] = to.path.substring(1).split('/');
		if (!controller) controller = 'index';
		if (!action) action = 'index';
		if (['welcome', 'index', 'msg'].indexOf(controller) > -1) {
			next();
			return;
		}

		var auth = Cookies.get("auth");
		var userid = Cookies.get("userid");
		var username = Cookies.get("username");
		var groupid = Cookies.get("groupid");
		var power = Cookies.get("power");

		if (!parseInt(userid)) {
			uni.reLaunch({
				url: "/pages/welcome/login"
			});
			return;
		}
		if (parseInt(groupid) == 1) {
			next();
			return;
		}


		//免验证
		if (['home', 'safe'].indexOf(controller) > -1) {
			next();
			return;
		}
		//去服务端验证
		let data = await axios.post('/api/auth/check', {
			userid,
			controller,
			action
		});
		if (!parseInt(data.code)) {
			uni.reLaunch({
				url: "/pages/msg?code=403",
			});
			return;
		}


		next();
	}
});

// 全局路由后置守卫
router.afterEach((to, from) => {
	NProgress.done();

})

export {
	router,
	RouterMount
}
